using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Ajax;

namespace BurbleLite
{
	/// <summary>
	/// Summary description for burble.
	/// </summary>
	public class burble : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.TextBox txtUserName;
		protected System.Web.UI.WebControls.TextBox txtKey;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			if (SessionWrapper.UserName == "")
			{
				Response.Redirect("default.aspx");
			}

			if (this.IsPostBack == false)
			{
				this.txtKey.Text = SessionWrapper.PublicKey;
				this.txtUserName.Text = SessionWrapper.UserName;
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
		public string getMsg()
		{
			string username = SessionWrapper.UserName;
			string msgs = SessionWrapper.ChatHistory.GetUserMessages(username);
			
			if (msgs.Length > 2000)
			{
				msgs = msgs.Substring(0,2000);
			}
			CleanupUsers();
			return msgs;
		}

		[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
		public void sendMsg(string text)
		{
			SessionWrapper.ChatHistory.AddMessageToAllBuffers(text);
		}

		[Ajax.AjaxMethod(HttpSessionStateRequirement.ReadWrite)]
		public string getUsers()
		{
			string[] allusers = SessionWrapper.ChatHistory.GetUsers();
			string res = "";
			foreach (string str in allusers)
			{
				res += str + "<br>";
			}
			return res;
		}

		public void CleanupUsers()
		{
			if (DateTime.Now.AddSeconds(-60) > SessionWrapper.LastCleanup)
			{
				SessionWrapper.LastCleanup = DateTime.Now;
				string[] allusers = SessionWrapper.ChatHistory.GetUsers();
				foreach (string str in allusers)
				{
					UserBuffer ub = SessionWrapper.ChatHistory.GetUserBuffer(str);
					if (DateTime.Now.AddSeconds(-20) > ub.LastAccess)
					{
						SessionWrapper.ChatHistory.Buffers.Remove(str);
					}
				}
			}
		}

	}
}
